package com.dabai.applicationmanager.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import com.dabai.applicationmanager.databinding.ActivityAppDetailsBinding
import com.dabai.applicationmanager.dialog.MdcDialog
import com.dabai.applicationmanager.shizuku.Shell
import com.dabai.applicationmanager.shizuku.ShizukuShell
import com.dabai.applicationmanager.utils.OtherUtils
import com.dabai.dbutils.qrcode.QRCodeUtils
import com.dabai.dbutils.utils.AppUtils
import com.dabai.dbutils.utils.DateUtils
import com.dabai.dbutils.utils.ShellUtils
import com.dabai.uitools.base.BaseAppCompatActivity
import me.zhanghai.android.appiconloader.AppIconLoader
import android.app.PendingIntent

import android.content.pm.ShortcutInfo

import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon

import android.os.Build

import androidx.annotation.RequiresApi
import com.dabai.applicationmanager.R
import com.dabai.dbutils.toast.DBToast


class AppDetailsActivity : BaseAppCompatActivity() {

    private lateinit var ada: ActivityAppDetailsBinding
    lateinit var context: Context

    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ada = ActivityAppDetailsBinding.inflate(layoutInflater)
        setContentView(ada.root)

        context = this

        supportActionBar!!.setDisplayHomeAsUpEnabled(true)

        val packageName = intent.getStringExtra("packageName")

        val packageInfo: PackageInfo = packageManager.getPackageInfo(
            packageName!!, 0
        )
        val applicationInfo = packageInfo.applicationInfo

        val packageManager = this.packageManager

        val GET_ACTIVITIES = packageManager.getPackageInfo(
            packageName, PackageManager.GET_ACTIVITIES
        )
        val GET_PERMISSIONS = packageManager.getPackageInfo(
            packageName, PackageManager.GET_PERMISSIONS
        )


        val appDetailsContent = """
            版本名:${packageInfo.versionName}
            版本代码:${packageInfo.versionCode}
            包名:${applicationInfo.packageName}
            
            最低平台API:${applicationInfo.minSdkVersion}
            目标平台API:${applicationInfo.targetSdkVersion}
            
            uid:${applicationInfo.uid}
            冻结状态:${if (applicationInfo.enabled) "已启用" else "已停用"}
            系统应用:${
            if (AppUtils.isSystemApplication(
                    context,
                    applicationInfo.packageName
                )
            ) "是" else "否"
        }
         
         ${
            if (GET_ACTIVITIES.activities != null)
                "   活动数量: ${GET_ACTIVITIES.activities.size}" else ""
        }
         ${
            if (GET_PERMISSIONS.requestedPermissions != null)
                "   权限数量: ${GET_PERMISSIONS.requestedPermissions.size}" else ""
        }
    
            首次安装时间:${DateUtils.getTime("yyyy-MM-dd HH:mm:ss", packageInfo.firstInstallTime)}
            最后更新时间:${DateUtils.getTime("yyyy-MM-dd HH:mm:ss", packageInfo.lastUpdateTime)}
            
            安装包目录:${applicationInfo.sourceDir}
            
            数据目录:${applicationInfo.dataDir}
            lib目录:${applicationInfo.nativeLibraryDir}
            
        """.trimIndent()


        val appIconLoader = AppIconLoader(200, true, context)
        ada.imageView1.setImageBitmap(appIconLoader.loadIcon(applicationInfo))
        ada.imageView2.setImageBitmap(QRCodeUtils.createSimpleQrCodeBitmap("market://details?id=${applicationInfo.packageName}",500,500))

        ada.textView1.text = appDetailsContent
        ada.textView3.text = AppUtils.getApplicationNameByPackageName(context, applicationInfo.packageName)

        if (OtherUtils.getImplementWay(context) == 1) {
            ada.button1.visibility = View.GONE
        }

        ada.button1.setOnClickListener {

            MdcDialog.showConfirmDialog(context,
                "提示",
                "确定要强行停止应用嘛?",
                object : MdcDialog.OnConfirmDialogButtonListener {
                    override fun confirm() {
                        if (OtherUtils.getImplementWay(context) ==2) {
                            ShellUtils.execCommand("am force-stop $packageName",true)
                            DBToast.showPurpleToast(context, "已终止${AppUtils.getApplicationNameByPackageName(context, applicationInfo.packageName)}!")

                        }else if (OtherUtils.getImplementWay(context) ==3 ){
                            ShizukuShell.getInstance().exec(
                                Shell.Command(
                                    "am force-stop $packageName"
                                )
                            )
                            DBToast.showPurpleToast(context, "已终止${AppUtils.getApplicationNameByPackageName(context, applicationInfo.packageName)}!")
                        }

                    }
                    override fun cancel() {}
                }).window!!.setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via)

        }

       ada.button1.setOnLongClickListener {
           val intent = Intent()
           intent.setClassName("com.dabai.applicationmanager", "com.dabai.applicationmanager.ui.StopAppActivity")
           intent.putExtra("packageName",applicationInfo.packageName)
           intent.putExtra("name",AppUtils.getApplicationNameByPackageName(context, applicationInfo.packageName))

           OtherUtils.addShortCut(context, "终止$${AppUtils.getApplicationNameByPackageName(context, applicationInfo.packageName)}", R.mipmap.ic_fire, intent)
           true
       }

        ada.button2.setOnClickListener {
            AppUtils.openInstalledAppDetails(context, applicationInfo.packageName)
        }

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val itemId = item.itemId
        if (itemId == R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }



}